import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sj001/drawerHome.dart';
import 'package:sj001/user/UserData.dart';
import 'package:sj001/utils/Store.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({Key? key}) : super(key: key);

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  List<UserData> users = [];
  TextEditingController ctr = TextEditingController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initUser();
  }

  initUser() {
    Store.getInstance().then((store) {
      Object? obj = store.getString(StoreKeys.userName);
      if (obj != null && obj is String) {
        dynamic ret = jsonDecode(obj);
        if (ret is List) {
          users.clear();
          for (var e in ret) {
            users.add(UserData.fromJson(e));
          }
        }
      }
    });
  }

  onLogin() {
    if (ctr.text.trim().isEmpty) return;
    String userName = ctr.text.trim();
    List<UserData> filterList =
        users.where((element) => element.userName == userName).toList();
    UserData loginUser;
    if (filterList.isEmpty) {
      loginUser = UserData(userName: userName);
      users.add(loginUser);
      Store.getInstance().then((store) {
        store.setString(StoreKeys.userName, jsonEncode(users));
      });
    } else {
      loginUser = filterList.first;
    }

    UserManager.instance.userData = loginUser;

    Get.offAll(() => const DrawerHomePage());
  }

  onSelect(UserData user){
    ctr.text = user.userName??'';
    Get.back();
  }
  onMore() {
    if (users.isEmpty) return;
    Get.bottomSheet(
        Container(
          clipBehavior: Clip.antiAlias,
          decoration: const BoxDecoration(
            borderRadius: BorderRadius.only(
              topRight: Radius.circular(10),
              topLeft: Radius.circular(10),
            ),
            color: Colors.white
          ),
          padding: EdgeInsets.only(bottom: 30),
          child: ListView.builder(
            padding: EdgeInsets.zero,
            shrinkWrap: true,
            itemBuilder: (ctx, index) {
              return InkWell(onTap: ()=>onSelect(users[index]),child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    height: 44,
                    alignment: Alignment.center,
                    decoration: const BoxDecoration(color: Colors.white),
                    child: Text(users[index].userName ?? ''),
                  ),
                  Visibility(
                    visible: index != users.length-1,
                    child: const Divider(
                      height: 1,
                      color: Color(0x10000000),
                    ),
                  ),
                ],
              ),);
            },
            itemCount: users.length,
          ),
        ),
        ignoreSafeArea: false,
        barrierColor: Color(0x30000000));
  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.sizeOf(context);
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            SizedBox(
              width: size.width * 0.7,
              height: 50,
              child: Row(
                children: [
                  Expanded(
                    child: TextField(
                      controller: ctr,
                      decoration: const InputDecoration(
                        enabledBorder: OutlineInputBorder(),
                        focusedBorder: OutlineInputBorder(),
                        hintText: '请输入用户名',
                      ),
                      onSubmitted: (text) {
                        onLogin();
                      },
                    ),
                  ),
                  const SizedBox(width: 5),
                  InkWell(
                    onTap: onMore,
                    child: const Padding(
                      padding: EdgeInsets.all(5),
                      child: Icon(
                        Icons.arrow_drop_down_circle_outlined,
                        size: 30,
                        color: Colors.black,
                      ),
                    ),
                  )
                ],
              ),
            ),
            const SizedBox(height: 100),
            InkWell(
              onTap: onLogin,
              child: Container(
                width: size.width * 0.2,
                height: 50,
                decoration: BoxDecoration(
                  color: Colors.blue,
                  borderRadius: BorderRadius.circular(5),
                ),
                alignment: Alignment.center,
                child: const Text(
                  '登录',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 20,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
